<template>
	<view>
		<view class="page">
			<!-- 加载提示 -->
			<view v-if="loadingMsg" class="padding-main tc cr-grey">
				<view>{{ loadingMsg }}</view>
			</view>

			<!-- 主要内容 -->
			<view v-if="companyInfo" class="goods-item oh padding-main">
				<!-- 认证状态提示 -->
				<view v-if="companyInfo.id > 0" class="status-tips padding-main bg-white border-radius-main margin-bottom-main">
					<view v-if="companyInfo.status === 0" class="cr-orange">
						已提交审核，请耐心等待！审核前您还可以再编辑一次资料！（当前可编辑：{{ editNum }}次）
					</view>
					<view v-if="companyInfo.status === 1" class="cr-red">
						入驻失败，请重新编辑提交！失败原因：{{ companyInfo.admin_note }}
					</view>
					<view v-if="companyInfo.status === 2" class="cr-green">
						入驻成功！当前页面仅供查看！
					</view>
				</view>

				<!-- 表单 -->
				<form @submit="handleFormSubmit" class="form-container">
					<view class="bg-white padding-main border-radius-main">
						<!-- 行业分类 -->
						<view class="form-item-wrapper">
							<view class="form-label">
								行业分类<text class="required-mark">*</text>
							</view>
							<view class="form-content">
								<picker 
									v-if="isEditable" 
									name="category_id_key" 
									@change="handleCategoryChange" 
									:value="companyInfo.category_id_key" 
									:range="categoryList" 
									range-key="name"
								>
									<view :class="['picker-value', { 'placeholder': categoryList.length === 0 }]">
										{{ categoryDisplayValue }}
									</view>
								</picker>
								<view v-else class="display-value">
									{{ categoryDisplayValue }}
								</view>
							</view>
						</view>

						<!-- 公司名称 -->
						<view class="form-item-wrapper">
							<view class="form-label">
								公司名称<text class="required-mark">*</text>
							</view>
							<view class="form-content">
								<input 
									v-if="isEditable"
									type="text" 
									name="name" 
									class="input-field" 
									maxlength="200" 
									placeholder="请输入公司名称" 
									@blur="handleInputBlur" 
									data-field="name" 
									:value="companyInfo.name" 
								/>
								<view v-else class="display-value">
									{{ companyInfo.name }}
								</view>
							</view>
						</view>

						<!-- 联系人姓名 -->
						<view class="form-item-wrapper">
							<view class="form-label">
								联系人姓名<text class="required-mark">*</text>
							</view>
							<view class="form-content">
								<input 
									v-if="isEditable"
									type="text" 
									name="contact_name" 
									class="input-field" 
									maxlength="20" 
									placeholder="请输入联系人姓名" 
									@blur="handleInputBlur" 
									data-field="contact_name" 
									:value="companyInfo.contact_name" 
								/>
								<view v-else class="display-value">
									{{ companyInfo.contact_name }}
								</view>
							</view>
						</view>

						<!-- 联系电话 -->
						<view class="form-item-wrapper">
							<view class="form-label">
								联系电话<text class="required-mark">*</text>
							</view>
							<view class="form-content">
								<input 
									v-if="isEditable"
									type="text" 
									name="contact_tel" 
									maxlength="30" 
									class="input-field" 
									placeholder="请输入联系电话" 
									@blur="handleInputBlur" 
									data-field="contact_tel" 
									:value="companyInfo.contact_tel" 
								/>
								<view v-else class="display-value">
									{{ companyInfo.contact_tel }}
								</view>
							</view>
						</view>

						<!-- 所在地 -->
						<view class="form-item-wrapper">
							<view class="form-label">
								所在地<text class="required-mark">*</text>
							</view>
							<view class="form-content">
								<view v-if="isEditable && !isForbidChoiceRegion" class="region-picker">
									<!-- 省份 -->
									<view class="region-item">
										<picker 
											name="province" 
											@change="handleProvinceChange" 
											:value="provinceValue" 
											:range="provinceList" 
											range-key="name"
										>
											<view :class="['picker-value', { 'placeholder': provinceValue === null }]">
												{{ provinceDisplayValue }}
											</view>
										</picker>
									</view>
									<!-- 城市 -->
									<view class="region-item">
										<picker 
											v-if="provinceId" 
											name="city" 
											@change="handleCityChange" 
											:value="cityValue" 
											:range="cityList" 
											range-key="name"
										>
											<view :class="['picker-value', { 'placeholder': cityValue === null }]">
												{{ cityDisplayValue }}
											</view>
										</picker>
										<text v-else class="placeholder" @tap="handleRegionError('请先选择省份')">
											请选择城市
										</text>
									</view>
									<!-- 区县 -->
									<view class="region-item">
										<picker 
											v-if="cityId" 
											name="county" 
											@change="handleCountyChange" 
											:value="countyValue" 
											:range="countyList" 
											range-key="name"
										>
											<view :class="['picker-value', { 'placeholder': countyValue === null }]">
												{{ countyDisplayValue }}
											</view>
										</picker>
										<text v-else class="placeholder" @tap="handleRegionError('请先选择城市')">
											请选择区县
										</text>
									</view>
								</view>
								<view v-else class="display-value">
									{{ regionDisplayValue }}
								</view>
							</view>
						</view>

						<!-- 详细地址 -->
						<view class="form-item-wrapper">
							<view class="form-label">
								详细地址<text class="required-mark">*</text>
								<text v-if="enableMapStatus && isEditable" class="fr cr-main" style="font-size: 28rpx;" @tap="handleChooseLocation">
									选择定位
								</text>
							</view>
							<view class="form-content address-content">
								<input 
									v-if="isEditable"
									type="text" 
									name="address" 
									:value="companyInfo.address || ''" 
									maxlength="80" 
									:class="['input-field', { 'with-map-icon': enableMapStatus }]" 
									placeholder="详细地址1~80个字符" 
									@blur="handleInputBlur" 
									data-field="address"
								/>
								<view v-else class="display-value">
									{{ companyInfo.address }}
								</view>
								<view 
									v-if="enableMapStatus && isEditable" 
									@tap="handleChooseLocation" 
									class="map-icon"
								>
									<text class="icon-location">📍</text>
								</view>
							</view>
							<view v-if="locationInfo" class="cr-main" style="font-size: 24rpx; margin-top: 10rpx;">
								{{ locationInfo }}
							</view>
						</view>

						<!-- 协议 -->
						<view v-if="isEditable" class="agreement-wrapper">
							<view class="agreement-checkbox" @tap="handleAgreementChange">
								<radio-group>
									<label>
										<radio value="agreement" color="#36abff" :checked="agreementStatus" />
									</label>
								</radio-group>
							</view>
							<view class="agreement-text">
								<text>我已阅读并同意 </text>
								<text class="cr-main" @tap="handleShowAgreement">《入驻协议》</text>
							</view>
						</view>

						<!-- 提交按钮 -->
						<view v-if="isEditable" class="submit-wrapper">
							<!-- 根据协议状态动态改变按钮颜色 -->
							<button 
								:class="['submit-btn', { 'active': agreementStatus }]"
								type="default" 
								form-type="submit" 
								:disabled="isSubmitting"
							>
								提交
							</button>
						</view>
					</view>
				</form>

				<!-- 协议弹窗 -->
				<component-popup 
					:propShow="showAgreementPopup" 
					propPosition="bottom" 
					@onclose="handleCloseAgreement"
				>
					<view class="agreement-popup">
						<view class="popup-header">
							<view class="popup-close" @tap="handleCloseAgreement">
								<icon type="clear" size="20"></icon>
							</view>
						</view>
						<view class="popup-content">
							<view class="popup-title">入驻协议</view>
							<view v-if="agreementList.length > 0" class="agreement-content">
								<view v-for="(item, index) in agreementList" :key="index" class="agreement-item">
									{{ item }}
								</view>
							</view>
						</view>
						<!-- 添加固定底部容器，确保按钮始终可见 -->
						<view v-if="isEditable" class="agreement-footer">
							<button 
								class="agreement-confirm-btn" 
								@tap="handleConfirmAgreement"
							>
								同意协议
							</button>
						</view>
					</view>
				</component-popup>
			</view>

			<!-- 底部 -->
			<component-classinfo-footer :propBaseData="baseData"></component-classinfo-footer>
		</view>
	</view>
</template>

<script>
const app = getApp();
import componentPopup from "@/components/popup/popup";
import componentClassinfoFooter from '../public/footer';
import { classinfo_base_info } from '@/pages/fcc/classinfo/public/common.js';

export default {
	components: {
		componentPopup,
		componentClassinfoFooter
	},

	data() {
		return {
			params: null,
			loadingMsg: '',
			baseData: null,
			companyInfo: null,
			categoryList: [],
			agreementList: [],
			
			// 地区相关
			provinceList: [],
			cityList: [],
			countyList: [],
			provinceId: null,
			cityId: null,
			countyId: null,
			provinceValue: null,
			cityValue: null,
			countyValue: null,
			
			// 配置
			enableMapStatus: 1,
			isForbidChoiceRegion: 0,
			
			// 状态
			editNum: 0,
			agreementStatus: false,
			showAgreementPopup: false,
			isSubmitting: false,
			locationInfo: '',
			locationCacheKey: app.globalData.data.cache_userlocation_key,
			
			editorPathType: 'classinfo-company',
			templateId: null,
			is_user_address_location_discern: 0,
		};
	},

	computed: {
		// 是否可编辑
		isEditable() {
			return this.companyInfo && (this.companyInfo.status === 0 || this.companyInfo.status === 1 || !this.companyInfo.id);
		},

		// 行业分类显示值
		categoryDisplayValue() {
			if (this.categoryList.length === 0) {
				return '请选择行业分类';
			}
			const selected = this.categoryList[this.companyInfo.category_id_key];
			return selected ? selected.name : '请选择行业分类';
		},

		// 省份显示值
		provinceDisplayValue() {
			if (this.provinceValue === null) return '请选择省份';
			const selected = this.provinceList[this.provinceValue];
			return selected ? selected.name : '请选择省份';
		},

		// 城市显示值
		cityDisplayValue() {
			if (this.cityValue === null) return '请选择城市';
			const selected = this.cityList[this.cityValue];
			return selected ? selected.name : '请选择城市';
		},

		// 区县显示值
		countyDisplayValue() {
			if (this.countyValue === null) return '请选择区县';
			const selected = this.countyList[this.countyValue];
			return selected ? selected.name : '请选择区县';
		},

		// 地区显示值（只读时）
		regionDisplayValue() {
			if (!this.companyInfo) return '';
			const parts = [];
			if (this.companyInfo.province_name) parts.push(this.companyInfo.province_name);
			if (this.companyInfo.city_name) parts.push(this.companyInfo.city_name);
			if (this.companyInfo.county_name) parts.push(this.companyInfo.county_name);
			return parts.join('');
		}
	},

	onLoad(params) {
		this.params = params;
		this.init();
	},

	onShow() {
		app.globalData.page_event_onshow_handle();
		this.initLocationData();
	},

	onReady() {
		this.removeLocationCache();
	},

	onPullDownRefresh() {
		this.init();
	},

	methods: {
		// 初始化
		async init() {
			try {
				const baseData = await classinfo_base_info();
				this.baseData = baseData;
				await this.initCompanyInfoFromCache();
				await this.initData();
			} catch (error) {
				console.error('初始化失败:', error);
				uni.stopPullDownRefresh();
			}
		},

		// 初始化数据
		async initData() {
			const user = app.globalData.get_user_info(this, "initData");
			if (!user) {
				uni.stopPullDownRefresh();
				app.globalData.page_share_handle();
				return;
			}

			try {
				await this.getProvinceList();
				await this.getCompanyData();
				app.globalData.page_share_handle();
			} catch (error) {
				console.error('获取数据失败:', error);
				uni.stopPullDownRefresh();
			}
		},

		// 从缓存初始化公司信息
		initCompanyInfoFromCache() {
			return new Promise((resolve) => {
				uni.getStorage({
					key: 'classinfo_company_auth_info',
					success: (res) => {
						if (res.data) {
							this.companyInfo = res.data;
							this.agreementStatus = res.data.agreement_status || false;
							if (res.data.province) {
								this.provinceId = res.data.province;
							}
							if (res.data.city) {
								this.cityId = res.data.city;
							}
							if (res.data.county) {
								this.countyId = res.data.county;
							}
						}
					},
					complete: () => {
						resolve();
					}
				});
			});
		},

		// 获取公司数据
		async getCompanyData() {
			uni.request({
				url: app.globalData.get_request_url("detail", "company", "classinfo"),
				method: "POST",
				data: this.params,
				dataType: "json",
				success: (res) => {console.log(res);
					if (res.data.code === 0) {
						const data = res.data.data || null;
						const companyData = data.data || null;
						
						this.categoryList = data.category || [];
						this.agreementList = data.xieyi || [];
						this.editorPathType = data.editor_path_type || 'classinfo-company';
						this.templateId = data.tempid01 || null;
						
						this.is_user_address_location_discern = app.globalData.get_config('plugins_base.intellectstools.data.is_user_address_location_discern', 0);

						const companyId = companyData ? parseInt(companyData.id) : 0;
						const companyStatus = companyData ? parseInt(companyData.status) : 0;

						// 设置公司信息
						if (companyId > 0) {
							this.companyInfo = companyData;
							this.companyInfo.type = 0;
							uni.setStorageSync('classinfo_company_auth_info', companyData);
							
							// 计算可编辑次数
							const editNum = parseInt(data.edit_num) - parseInt(companyData.edit_num);
							this.editNum = editNum;

							// 设置地区ID
							this.provinceId = companyData.province || null;
							this.cityId = companyData.city || null;
							this.countyId = companyData.county || null;
						} else {
							// 新建时从缓存读取
							const cachedInfo = uni.getStorageSync('classinfo_company_auth_info');
							if (cachedInfo) {
								this.companyInfo = cachedInfo;
								if (cachedInfo.province) {
									this.provinceId = cachedInfo.province;
								}
								if (cachedInfo.city) {
									this.cityId = cachedInfo.city;
								}
								if (cachedInfo.county) {
									this.countyId = cachedInfo.county;
								}
								if (cachedInfo.category_id_key !== undefined && cachedInfo.category_id_key !== null) {
									this.companyInfo.category_id_key = cachedInfo.category_id_key;
									// 从分类列表中获取对应的 category_id
									if (this.categoryList.length > 0 && this.categoryList[cachedInfo.category_id_key]) {
										this.companyInfo.category_id = this.categoryList[cachedInfo.category_id_key].id;
									}
								}
							} else if (!this.companyInfo) {
								this.companyInfo = {
									id: 0,
									type: 0,
									status: 0,
									category_id_key: 0,
									category_id: null,
									name: '',
									contact_name: '',
									contact_tel: '',
									province: null,
									city: null,
									county: null,
									address: '',
									agreement_status: false
								};
								uni.setStorageSync('classinfo_company_auth_info', this.companyInfo);
							}
						}

						// 填充地区数据
						this.fillRegionData();
					} else {
						this.loadingMsg = res.data.msg;
						if (app.globalData.is_login_check(res.data)) {
							app.globalData.showToast(res.data.msg);
						}
					}
				},
				fail: () => {
					app.globalData.showToast('获取数据失败，请重试');
				},
				complete: () => {
					uni.stopPullDownRefresh();
				}
			});
		},

		// 填充地区数据
		fillRegionData() {
			if (this.provinceId) {
				this.getCityList(true);
			} else {
				this.initRegionValue();
			}
			
			if (this.cityId) {
				this.getCountyList(true);
			}
			//this.getCityList(true);
			//this.getCountyList(true);
		},

		// 初始化地区值
		initRegionValue() {
			this.provinceValue = this.getRegionValue("provinceList", "provinceId");
			this.cityValue = this.getRegionValue("cityList", "cityId");
			this.countyValue = this.getRegionValue("countyList", "countyId");
		},

		// 获取地区值索引
		getRegionValue(listName, idName) {
			const list = this[listName];
			const id = this[idName];
			let value = null;
			list.forEach((item, index) => {
				if (item.id === id) {
					value = index;
					return false;
				}
			});
			return value;
		},

		// 获取省份列表
		getProvinceList() {
			return new Promise((resolve, reject) => {
				uni.request({
					url: app.globalData.get_request_url("index", "region"),
					method: "POST",
					data: {},
					dataType: "json",
					success: (res) => {
						if (res.data.code === 0) {
							this.provinceList = res.data.data;
							this.initRegionValue();
							resolve();
						} else {
							app.globalData.showToast(res.data.msg);
							reject(res.data.msg);
						}
					},
					fail: () => {
						app.globalData.showToast('获取省份列表失败');
						reject('获取省份列表失败');
					}
				});
			});
		},

		// 获取城市列表
		getCityList(isInit = false) {
			if (!this.provinceId) return;

			uni.request({
				url: app.globalData.get_request_url("index", "region"),
				method: "POST",
				data: { pid: this.provinceId },
				dataType: "json",
				success: (res) => {
					if (res.data.code === 0) {
						this.cityList = res.data.data;
						if (isInit) {
							this.initRegionValue();
						}
					} else {
						app.globalData.showToast(res.data.msg);
					}
				},
				fail: () => {
					app.globalData.showToast('获取城市列表失败');
				}
			});
		},

		// 获取区县列表
		getCountyList(isInit = false) {
			if (!this.cityId) return;

			uni.request({
				url: app.globalData.get_request_url("index", "region"),
				method: "POST",
				data: { pid: this.cityId },
				dataType: "json",
				success: (res) => {
					if (res.data.code === 0) {
						this.countyList = res.data.data;
						if (isInit) {
							this.initRegionValue();
						}
					} else {
						app.globalData.showToast(res.data.msg);
					}
				},
				fail: () => {
					app.globalData.showToast('获取区县列表失败');
				}
			});
		},

		// 处理行业分类改变
		handleCategoryChange(e) {
			const index = parseInt(e.detail.value) || 0;
			if (index >= 0 && this.categoryList.length > 0) {
				this.companyInfo.category_id_key = index;
				this.companyInfo.category_id = this.categoryList[index].id;
				this.saveToCache();
			}
		},

		// 处理输入框失焦
		handleInputBlur(e) {
			const field = e.currentTarget.dataset.field;
			const value = e.detail.value;
			if (this.companyInfo) {
				this.companyInfo[field] = value;
				this.saveToCache();
			}
		},

		// 处理省份改变
		handleProvinceChange(e) {
			const index = e.detail.value || 0;
			if (index >= 0) {
				const data = this.provinceList[index];
				this.provinceValue = index;
				this.provinceId = data.id;
				this.cityValue = null;
				this.countyValue = null;
				this.cityId = null;
				this.countyId = null;
				
				this.companyInfo.province = data.id;
				this.companyInfo.province_id = data.id;
				this.saveToCache();
				
				this.getCityList();
			}
		},

		// 处理城市改变
		handleCityChange(e) {
			const index = e.detail.value || 0;
			if (index >= 0) {
				const data = this.cityList[index];
				this.cityValue = index;
				this.cityId = data.id;
				this.countyValue = null;
				this.countyId = null;
				
				this.companyInfo.city = data.id;
				this.companyInfo.city_id = data.id;
				this.saveToCache();
				
				this.getCountyList();
			}
		},

		// 处理区县改变
		handleCountyChange(e) {
			const index = e.detail.value || 0;
			if (index >= 0) {
				const data = this.countyList[index];
				this.countyValue = index;
				this.countyId = data.id;
				
				this.companyInfo.county = data.id;
				this.companyInfo.county_id = data.id;
				this.saveToCache();
			}
		},

		// 处理地区选择错误
		handleRegionError(msg) {
			app.globalData.showToast(msg);
		},

		// 选择地理位置
		handleChooseLocation() {
			this.saveToCache();
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/common/open-setting-location/open-setting-location'
				});
			}, 300);
		},

		// 初始化位置数据
		initLocationData() {
			const locationData = uni.getStorageSync(this.locationCacheKey);
			if (locationData) {
				const data = {
					name: locationData.name || null,
					address: locationData.address || null,
					lat: locationData.lat || null,
					lng: locationData.lng || null
				};
				
				const locationInfo = `定位信息：${data.name}, ${data.address}, ${data.lat}, ${data.lng}`;
				this.locationInfo = locationInfo;
				
				if (this.companyInfo) {
					this.companyInfo.lat = data.lat || 0;
					this.companyInfo.lng = data.lng || 0;
					this.companyInfo.location_info = locationInfo;
					this.saveToCache();
				}
				
				// 是否开启地理位置选择后自动识别
				if (this.is_user_address_location_discern == 1) {
					data['status'] = 1; // 位置已选择
				    this.address_discern_handle(data, 0, 1);
				}
				
				this.removeLocationCache();
			} else {
				const cachedInfo = uni.getStorageSync('classinfo_company_auth_info');
				if (cachedInfo && cachedInfo.location_info) {
					this.locationInfo = cachedInfo.location_info;
				}
			}
		},
		
		// 地址识别处理
		// data 地址信息
		// is_user 是否解析用户信息（0, 1）
		// type 0 用户输入地址信息识别, 1用户选择地理位置识别
		address_discern_handle(data, is_user = 0, type = 0) {
		    data['is_user'] = is_user;
		    uni.showLoading({
		        title: this.$t('common.processing_in_text'),
		        mask: true,
		    });
		    uni.request({
		        url: app.globalData.get_request_url('address', 'index', 'intellectstools'),
		        method: 'POST',
		        data: data,
		        dataType: 'json',
		        success: (res) => {
		            uni.hideLoading();
		            if (res.data.code == 0) {
		                var temp_ads = this.address_data || {};
		                var ads_data = res.data.data;
						// 设置地区ID
						if((ads_data.province || null) != null)
						{
							this.provinceId = ads_data.province || null;
							this.companyInfo.province = ads_data.province;
							this.saveToCache();
						}
						if((ads_data.city || null) != null)
						{
							this.cityId = ads_data.city || null;
							this.companyInfo.city = ads_data.city;
							this.saveToCache();
						}
						if((ads_data.county || null) != null)
						{
							this.countyId = ads_data.county || null;
							this.companyInfo.county = ads_data.county;
							this.saveToCache();
						}
						
						if (this.companyInfo && ads_data.address) {
							this.companyInfo.address = ads_data.address;
							this.saveToCache();
						}
		                // 重新填充地区数据
		                this.fillRegionData();
		            } else {
		                if (app.globalData.is_login_check(res.data)) {
		                    app.globalData.showToast(res.data.msg);
		                } else {
		                    app.globalData.showToast(this.$t('common.sub_error_retry_tips'));
		                }
		            }
		        },
		        fail: () => {
		            uni.hideLoading();
		            app.globalData.showToast(this.$t('common.internet_error_tips'));
		        },
		    });
		},

		// 移除位置缓存
		removeLocationCache() {
			uni.removeStorage({
				key: this.locationCacheKey
			});
		},

		// 处理协议改变
		handleAgreementChange() {
			this.agreementStatus = !this.agreementStatus;
			if (this.companyInfo) {
				this.companyInfo.agreement_status = this.agreementStatus;
				this.saveToCache();
			}
		},

		// 显示协议
		handleShowAgreement() {
			if (!app.globalData.is_single_page_check()) {
				return false;
			}
			this.showAgreementPopup = true;
		},

		// 关闭协议
		handleCloseAgreement() {
			this.showAgreementPopup = false;
		},

		// 确认协议
		handleConfirmAgreement() {
			this.agreementStatus = true;
			if (this.companyInfo) {
				this.companyInfo.agreement_status = true;
				this.saveToCache();
			}
			this.showAgreementPopup = false;
		},

		// 保存到缓存
		saveToCache() {
			if (this.companyInfo) {
				uni.setStorageSync('classinfo_company_auth_info', this.companyInfo);
			}
		},

		// 提交表单
		handleFormSubmit() {
			// 检查协议
			if (!this.agreementStatus) {
				app.globalData.showToast('请先阅读并同意入驻协议');
				return false;
			}

			const formData = { ...this.companyInfo };
			formData.params = this.params;
			formData.type = 0;

			// 数据校验
			const validation = [
				{ fields: "category_id", msg: "请选择行业分类" },
				{ fields: "name", msg: "请输入公司名称" },
				{ fields: "contact_name", msg: "请输入联系人姓名" },
				{ fields: "contact_tel", msg: "请输入联系电话" },
				{ fields: "province", msg: "请选择省份" },
				{ fields: "city", msg: "请选择城市" },
				{ fields: "county", msg: "请选择区县" },
				{ fields: "address", msg: "请输入详细地址" }
			];

			if (app.globalData.fields_check(formData, validation)) {
				// 清除缓存
				uni.removeStorageSync('classinfo_company_auth_info');

				this.isSubmitting = true;
				uni.showLoading({
					title: '提交中...'
				});

				uni.request({
					url: app.globalData.get_request_url("companysave", "company", "classinfo"),
					method: "POST",
					data: formData,
					dataType: "json",
					success: (res) => {console.log(res);
						uni.hideLoading();
						if (res.data.code === 0) {
							app.globalData.showToast(res.data.msg, "success");

							// 订阅消息
							if (this.templateId) {
								uni.requestSubscribeMessage({
									tmplIds: [this.templateId],
									complete: () => {
										setTimeout(() => {
											uni.navigateBack();
										}, 1000);
									}
								});
							} else {
								setTimeout(() => {
									this.init();
									this.isSubmitting = false;
								}, 1000);
							}
						} else {
							this.isSubmitting = false;
							if (app.globalData.is_login_check(res.data)) {
								app.globalData.showToast(res.data.msg);
							} else {
								app.globalData.showToast('提交失败，请重试');
							}
						}
					},
					fail: () => {
						this.isSubmitting = false;
						uni.hideLoading();
						app.globalData.showToast('网络错误，请重试');
					}
				});
			}
		}
	}
};
</script>

<style>
.page {
	background-color: #f5f5f5;
	min-height: 100vh;
	/* 添加底部安全距离，避免被tabbar遮挡 */
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
	padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
}

.status-tips {
	font-size: 28rpx;
	line-height: 1.6;
}

.form-container {
	width: 100%;
}

.form-item-wrapper {
	padding: 30rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.form-item-wrapper:last-child {
	border-bottom: none;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	line-height: 1.5;
}

.required-mark {
	color: #ff0000;
	margin-left: 4rpx;
}

.form-content {
	font-size: 28rpx;
}

.picker-value {
	color: #333;
	/* 增加输入框高度和padding，确保文字完整显示 */
	height: 80rpx;
	line-height: 80rpx;
	padding: 0 20rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	box-sizing: border-box;
	display: flex;
	align-items: center;
}

.picker-value.placeholder {
	color: #999;
}

.input-field {
	width: 100%;
	/* 修复输入框高度和padding，确保文字完整显示 */
	height: 80rpx;
	line-height: 80rpx;
	padding: 0 20rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #333;
	box-sizing: border-box;
}

.display-value {
	padding: 20rpx 0;
	color: #333;
	font-size: 28rpx;
	line-height: 1.6;
	min-height: 40rpx;
}

.region-picker {
	display: flex;
	gap: 20rpx;
	flex-wrap: wrap;
}

.region-item {
	flex: 1;
	min-width: 180rpx;
}

.region-item .picker-value,
.region-item .placeholder {
	font-size: 26rpx;
	/* 统一地区选择器的高度 */
	height: 70rpx;
	line-height: 70rpx;
	padding: 0 15rpx;
	box-sizing: border-box;
}

.region-item .placeholder {
	display: block;
	color: #999;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	text-align: center;
}

.address-content {
	position: relative;
	display: flex;
	align-items: center;
}

.input-field.with-map-icon {
	padding-right: 80rpx;
}

.map-icon {
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	display: flex;
	align-items: center;
	justify-content: center;
	width: 60rpx;
	height: 60rpx;
}

.icon-location {
	font-size: 40rpx;
}

.agreement-wrapper {
	display: flex;
	align-items: center;
	margin-top: 40rpx;
	font-size: 26rpx;
}

.agreement-checkbox {
	transform: scale(0.8);
	margin-right: -10rpx;
}

.agreement-text {
	color: #666;
	line-height: 1.6;
}

.submit-wrapper {
	margin-top: 40rpx;
}

/* 优化提交按钮样式，默认灰色，同意协议后变蓝色 */
.submit-btn {
	width: 100%;
	background-color: #d0d0d0;
	color: #fff;
	border-radius: 8rpx;
	font-size: 32rpx;
	height: 88rpx;
	line-height: 88rpx;
	padding: 0;
	border: none;
	transition: background-color 0.3s ease;
}

.submit-btn.active {
	background-color: #36abff;
	color:#fff !important;
}

.submit-btn[disabled] {
	background-color: #ccc;
}

/* 优化弹窗样式，确保按钮可见 */
.agreement-popup {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	max-height: 80vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.popup-header {
	display: flex;
	justify-content: flex-end;
	padding: 30rpx 30rpx 10rpx;
	flex-shrink: 0;
}

.popup-close {
	cursor: pointer;
}

.popup-content {
	flex: 1;
	overflow-y: auto;
	padding: 0 0rpx 20rpx;
}

.popup-title {
	font-size: 32rpx;
	font-weight: bold;
	text-align: center;
	margin-bottom: 30rpx;
}

.agreement-content {
	margin: 20rpx;
}

.agreement-item {
	font-size: 28rpx;
	line-height: 1.8;
	color: #666;
	margin-bottom: 20rpx;
}

/* 固定底部按钮容器，确保始终可见 */
.agreement-footer {
	padding: 20rpx 30rpx;
	padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	background-color: #fff;
	border-top: 1rpx solid #f0f0f0;
	flex-shrink: 0;
}

.agreement-confirm-btn {
	width: 100%;
	background-color: #36abff;
	color: #fff;
	border-radius: 8rpx;
	font-size: 32rpx;
	height: 88rpx;
	line-height: 88rpx;
	padding: 0;
	border: none;
	box-sizing: border-box;
}

/* 工具类 */
.tc { text-align: center; }
.oh { overflow: hidden; }
.fl { float: left; }
.fr { float: right; }
.pr { position: relative; }
.pa { position: absolute; }
.cp { cursor: pointer; }
.cr-grey { color: #999; }
.cr-red { color: #ff0000; }
.cr-green { color: #09bb07; }
.cr-orange { color: #ff9500; }
.cr-main { color: #36abff; }
.bg-white { background-color: #fff; }
.padding-main { padding: 30rpx; }
.margin-bottom-main { margin-bottom: 30rpx; }
.border-radius-main { border-radius: 12rpx; }
</style>
